<!-- 管理 -->
<template>
  <div class="app-container">
    <!-- 列表 -->
    <el-col>
      <div v-if="isShowSearchBtn" class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="关键字" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="关键字"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="状态" prop="is_hid">
            <el-select
              v-model="queryParams.is_hid"
              placeholder="全部"
              clearable
              class="!w-[100px]"
            >
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery"
              ><i-ep-search />搜索</el-button
            >
            <el-button @click="resetQuery">
              <i-ep-refresh />
              重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never" class="table-container">
        <template #header>
          <div class="flex justify-between">
            <div>
              <el-button
                v-hasPerm="['flow@add']"
                type="success"
                @click="openDialog()"
                ><i-ep-plus />新增</el-button
              >
              <el-button
                v-hasPerm="['flow@del']"
                type="danger"
                v-if="removeIds.length > 0"
                @click="handleDelete()"
                ><i-ep-delete />删除</el-button
              >
            </div>
            <div>
              <el-button
                class="ml-3"
                @click="handleSearchShowBtn"
                icon="Search"
                circle
              />
              <el-button
                class="ml-3"
                title="刷新"
                @click="handleQuery"
                icon="Refresh"
                circle
              />
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="pageData"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
          default-expand-all
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            key="id"
            label="ID"
            align="center"
            prop="id"
            width="100"
            sortable="custom"
          />
          <el-table-column label="" align="center">
            <template #default="scope">
              <el-icon :size="24">
                <component :is="scope.row.icon" />
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column label="流程名称" align="center" prop="title" />
          <el-table-column
            label="流程类型"
            align="center"
            prop="category_name"
          />
          <el-table-column label="业务编码" align="center" prop="code" />
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="状态" align="center" prop="is_hid">
            <template #default="scope">
              <el-tag
                effect="dark"
                :type="scope.row.is_hid == 0 ? 'success' : 'danger'"
              >
                {{ scope.row.is_hid == 0 ? "启用" : "禁用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="created_at" />
          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                v-hasPerm="['flow@edit']"
                type="success"
                circle
                title="编辑"
                @click="openDialog(scope.row.id)"
                ><i-ep-edit
              /></el-button>
              <el-button
                v-hasPerm="['flow@flowuser']"
                type="primary"
                circle
                title="流程设计"
                @click="openReviewDrawer(scope.row.id)"
                ><i-ep-paperclip
              /></el-button>
              <el-button
                v-hasPerm="['flow@del']"
                circle
                type="danger"
                title="删除"
                @click="handleDelete(scope.row.id)"
                ><i-ep-delete
              /></el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.p"
          v-model:limit="queryParams.limit"
          @pagination="handleQuery"
        />
      </el-card>
    </el-col>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 新增/编辑表单 -->
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="业务类型" prop="category_id">
          <el-select
            v-model="formData.category_id"
            placeholder="请选择业务类型"
            @change="categoryType"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务编码" prop="code">
          <el-input
            v-model="formData.code"
            placeholder="请输入业务编码，以字母数据命名"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            :min="0"
            style="width: 100px"
          />
        </el-form-item>

        <el-form-item label="状态" prop="is_hid">
          <el-radio-group v-model="formData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="viewDrawer" title="流程设计" direction="rtl" size="85%">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="flow">
            <div v-for="(item, index) in stampLst" :key="index" class="flow-pr">
              <div
                class="flow-container"
                :class="{ active: index == current1 }"
                @click="flowTab(item, index)"
              >
                <el-button type="warning" icon="stamp" circle />
                <el-text class="mx-2" style="margin-left: 10px">{{
                  item.title
                }}</el-text>
                <div class="stamp-close" v-if="index > 0">
                  <el-button
                    type="danger"
                    @click="flowRemove(item.type, index)"
                    icon="close"
                    plain
                    circle
                  />
                </div>
                <el-dropdown style="position: absolute; right: 25px; top: 14%">
                  <span class="el-dropdown-link">
                    {{ item.label }} <el-icon><ArrowRight /></el-icon
                  ></span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        @click="flowSet(items, 1, i, index)"
                        v-for="(items, i) in flowMenu"
                        :key="i"
                        >{{ items.label }}</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="flow-line">
                <i class="flow-line-inner"></i>
              </div>
              <div class="flow-add-button">
                <el-button icon="Plus" circle @click="flowAdd(item.type)" />
              </div>
            </div>
            <div
              v-for="(item, index) in promotionLst"
              :key="index"
              class="flow-pr"
            >
              <div
                class="flow-container"
                :class="{ active: index == current2 }"
                @click="flowTab(item, index)"
              >
                <el-button type="primary" icon="promotion" circle />
                <el-text class="mx-2" style="margin-left: 10px">{{
                  item.title
                }}</el-text>
                <div class="stamp-close">
                  <el-button
                    type="danger"
                    @click="flowRemove(item.type, index)"
                    icon="close"
                    plain
                    circle
                  />
                </div>
                <el-dropdown style="position: absolute; right: 25px; top: 14%">
                  <span class="el-dropdown-link">
                    {{ item.label }} <el-icon><ArrowRight /></el-icon
                  ></span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        @click="flowSet(items, 2, i, index)"
                        v-for="(items, i) in flowMenu"
                        :key="i"
                        >{{ items.label }}</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="flow-line">
                <i class="flow-line-inner"></i>
              </div>
              <div class="flow-add-button">
                <el-button icon="Plus" circle @click="flowAdd(item.type)" />
              </div>
            </div>
            <div style="position: relative; height: 128px">
              <div
                class="flow-container"
                :class="{ active: current3 }"
                @click="flowTab({ type: 3 }, -1)"
              >
                <el-button type="primary" icon="promotion" circle />
                <el-text class="mx-2" style="margin-left: 10px">抄送人</el-text>
                <el-dropdown style="position: absolute; right: 25px; top: 14%">
                  <span class="el-dropdown-link">
                    {{ menuLabel }} <el-icon><ArrowRight /></el-icon
                  ></span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        v-for="(items, i) in flowMenu"
                        @click="flowSet(items, 2, i, -1)"
                        :key="i"
                        >{{ items.label }}</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="flow-line-promotion">
                <i class="flow-line-inner"></i>
              </div>
              <div class="flow-add-button-promotion">
                <el-button icon="Plus" @click="flowAdd(2)" circle />
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="18">
          <div>
            <el-form
              ref="formRef"
              :model="formData"
              :rules="rules"
              label-width="120px"
              v-if="currentType > 0"
            >
              <el-form-item label="审批人" v-if="flowType != 0">
                <el-select
                  v-model="formData.type"
                  placeholder="请选择审批人"
                  style="width: 140px"
                  @change="changeFlowType"
                >
                  <el-option
                    v-for="item in flowMenu"
                    :key="item.type"
                    :label="item.label"
                    :value="item.type"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="主管" v-if="flowType == 2">
                <el-select
                  v-model="checkUserIds"
                  multiple
                  clearable
                  placeholder="请选择主管"
                  style="width: 280px"
                  @change="changeUserType"
                >
                  <el-option
                    v-for="item in flowOptionLst"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="角色" v-if="flowType == 3">
                <el-cascader
                  v-model="checkUserIds"
                  :options="flowOptionLst"
                  :props="cascaderProps"
                  :show-all-levels="false"
                  clearable
                  style="width: 280px"
                  @change="changeUserType"
                />
              </el-form-item>
              <el-form-item label="">
                <div
                  class="message-avatar"
                  v-for="item in checkUserLst"
                  :key="item.id"
                >
                  <el-avatar
                    :src="item.avatar"
                    :size="32"
                    class="role-avatar"
                    style="margin: 0 12px"
                  />
                  <el-icon
                    class="remove-user"
                    @click="addUser(item, 'remove')"
                    size="16"
                    ><Close
                  /></el-icon>
                </div>
              </el-form-item>
              <el-form-item
                label="多人审批"
                prop="type"
                v-if="checkUserNumber > 1 && currentType != 2"
              >
                <el-radio-group v-model="formData.approval_type">
                  <el-radio
                    :value="1"
                    border
                    style="display: flex; align-items: center"
                    >会签
                    <el-tooltip
                      content="需所有有人同意"
                      placement="bottom"
                      effect="light"
                      ><el-icon><QuestionFilled /></el-icon></el-tooltip
                  ></el-radio>
                  <el-radio
                    :value="2"
                    border
                    style="display: flex; align-items: center"
                    >或签
                    <el-tooltip
                      content="一人审批通过即可"
                      placement="bottom"
                      effect="light"
                      ><el-icon><QuestionFilled /></el-icon></el-tooltip
                  ></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="flowType === 1">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card shadow="never" class="table-container">
                  <el-tree
                    :data="orgTreeData"
                    :props="defaultProps"
                    :default-expand-all="true"
                    @node-click="handleOrg"
                  />
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card shadow="never" class="table-container">
                  <template #header>
                    <div class="flex justify-between">
                      <div style="display: inline-block">
                        <el-form
                          ref="queryUserFormRef"
                          :model="queryUserParams"
                          :inline="true"
                          style="margin-bottom: -16px"
                        >
                          <el-form-item prop="title" style="margin-right: 5px">
                            <el-input
                              v-model="queryUserParams.title"
                              placeholder="请输入用户名"
                              clearable
                              style="width: 150px"
                              @keyup.enter="handleUserQuery"
                            />
                          </el-form-item>
                          <el-form-item style="margin-right: 0">
                            <el-button type="primary" @click="handleUserQuery"
                              ><i-ep-search />搜索</el-button
                            >
                            <el-button @click="resetUserQuery">
                              <i-ep-refresh />
                              重置</el-button
                            >
                          </el-form-item>
                        </el-form>
                      </div>
                    </div>
                  </template>
                  <el-table :data="userList">
                    <el-table-column width="45px">
                      <template #default="scope">
                        <el-button
                          icon="Plus"
                          circle
                          @click="addUser(scope.row, 'add')"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      property="avatar"
                      label="头像"
                      width="65px"
                    >
                      <template #default="scope">
                        <el-avatar
                          :src="scope.row.avatar"
                          :size="32"
                          class="role-avatar"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column property="nickname" label="用户名" />
                    <el-table-column property="username" label="账号" />
                  </el-table>
                  <pagination
                    v-if="totalUser > 0"
                    v-model:total="totalUser"
                    v-model:page="queryUserParams.p"
                    v-model:limit="queryUserParams.limit"
                    @pagination="handleUserQuery"
                  />
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card shadow="never" class="table-container">
                  <template #header>
                    <div class="flex justify-between">
                      <span class="role-avatar"
                        >已选择：{{ checkUserNumber }}</span
                      >
                      <el-button
                        type="danger"
                        @click="addUser([], 'remove', true)"
                        circle
                        aria-label="移除"
                        ><i-ep-minus
                      /></el-button>
                    </div>
                  </template>
                  <el-table :data="checkUserLst">
                    <el-table-column width="45px">
                      <template #default="scope">
                        <el-button
                          type="danger"
                          icon="Minus"
                          circle
                          @click="addUser(scope.row, 'remove')"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      property="avatar"
                      label="头像"
                      width="65px"
                    >
                      <template #default="scope">
                        <el-avatar
                          :src="scope.row.avatar"
                          :size="32"
                          class="role-avatar"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column property="nickname" label="用户名" />
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="viewDrawer = false">关闭</el-button>
          <el-button @click="confirmFlow" type="primary">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Flow",
  inheritAttrs: false,
});

import {
  getFlowPage,
  addFlow,
  updateFlow,
  getFlowForm,
  deleteFlow,
  getOptions,
  addFlowUser,
  getFlowUserForm,
} from "@/api/flow";
import {
  FlowForm,
  FlowQuery,
  FlowPage,
  FlowOptions,
  FlowUserForm,
} from "@/api/flow/types";
import { getUserPage } from "@/api/role";
import { orgTree } from "@/api/organization";
import { UserQuery, UserPageVO } from "@/api/user/types";
import { getPositionAll } from "@/api/position";
import { getRoleOptions } from "@/api/role";
const options = ref<FlowOptions[]>(); // 下拉数据源
const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 表单
const isShowSearchBtn = ref(false);
const isShowForm = ref(false);
const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除ID集合 用于批量删除
const queryParams = reactive<FlowQuery>({
  p: 1,
  limit: 10,
});
const total = ref(0); // 数据总数
const pageData = ref<FlowPage[]>(); // 分页数据
const viewDrawer = ref(false);
const stampLst = ref([]);
const flowMenu = ref([
  {
    label: "指定人",
    type: 1,
  },
  {
    label: "直接主管",
    type: 2,
  },
  {
    label: "指定角色",
    type: 3,
  },
]);
const promotionLst = ref([]);
const flowType = ref(0);
const userList = ref<UserPageVO[]>();
const checkUserLst = ref<UserPageVO[]>();
const originalUserList = ref<UserPageVO[]>();
const checkUserIds: Ref<number[]> = ref([]);
const checkUserNumber = ref(0);
const totalUser = ref(0);
const currentId = ref(undefined);
const current1 = ref(-1);
const current2 = ref(-1);
const current3 = ref(false);
const currentType = ref(0);
const ccType = ref(0);
const ccPromotionLst = ref({
  type: 1,
  title: "审批人",
  label: "设置",
  user_ids: [],
  users: [],
  user_type: undefined,
  approval_type: undefined,
});
const queryUserParams = reactive<UserQuery>({
  p: 1,
  limit: 10,
});
const orgTreeData = ref<OptionType[]>(); //组织架构下拉数据源
const defaultProps = ref({
  children: "children",
  label: "title",
});
const menuLabel = ref("设置");
const positionLst = ref<OptionType[]>();
const roleLst = ref<OptionType[]>();
const flowOptionLst = ref<OptionType[]>();
const cascaderProps = ref({
  multiple: true,
  checkStrictly: true,
  emitPath: false,
});
// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

// 表单数据
const formData = reactive<FlowForm>({
  is_hid: 0,
  sort: 0,
});

// 校验规则
const rules = reactive({
  title: [{ required: true, message: "业务名称不能为空", trigger: "blur" }],
  category_id: [
    { required: true, message: "业务类型不能为空", trigger: "blur" },
  ],
});

/**新增流程*/
function flowAdd(type: number) {
  if (type == 1) {
    stampLst.value.push({
      type: type,
      user_type: undefined,
      title: "审批人",
      label: "设置",
      user_ids: [],
      users: [],
      approval_type: undefined,
    });
  } else {
    promotionLst.value.push({
      type: type,
      title: "抄送人",
      label: "设置",
      user_ids: [],
      users: [],
      user_type: undefined,
      approval_type: undefined,
    });
  }
  checkUserLst.value = [];
  formData.type = undefined;
  formData.approval_type = undefined;
  checkUserNumber.value = 0;
  flowType.value = 0;
}
/**移除流程*/
function flowRemove(type: number, index: number) {
  if (type == 1) {
    stampLst.value = stampLst.value.filter((item, i) => {
      return i !== index;
    });
  } else {
    promotionLst.value = promotionLst.value.filter((item, i) => {
      return i !== index;
    });
  }
  formData.type = undefined;
  formData.approval_type = undefined;
  flowType.value = 0;
}
/**设置审批人显示*/
function flowSet(item: any, type: number, i: number, index: number) {
  flowType.value = item.type;
  if (type == 2 && index == -1) {
    menuLabel.value = flowMenu.value[i].label;
    formData.type = flowType.value = ccType.value = item.type;
    ccPromotionLst.value.label = menuLabel.value;
    ccPromotionLst.value.user_type = item.type;
    ccPromotionLst.value.type = type;
    ccType.value = item.type;
    current3.value = true;
    checkUserLst.value = ccPromotionLst.value.users;
  }
  if (type == 1) {
    stampLst.value[index].label = flowMenu.value[i].label;
    stampLst.value[index].user_type = item.type;
    formData.type = flowType.value = stampLst.value[index].user_type;
    current1.value = index;
    checkUserLst.value = stampLst.value[index].users;
  }
  if (type == 2 && index != -1) {
    promotionLst.value[index].label = flowMenu.value[i].label;
    promotionLst.value[index].user_type = item.type;
    formData.type = flowType.value = promotionLst.value[index].user_type;
    current2.value = index;
    checkUserLst.value = promotionLst.value[index].users;
  }
  checkUserNumber.value = checkUserLst.value?.length;
  if (flowType.value == 2) {
    checkUserLst.value = [];
    flowOptionLst.value = positionLst.value;
    checkUserNumber.value = 0;
  }
  if (flowType.value == 3) {
    flowOptionLst.value = roleLst.value;
    checkUserLst.value = [];
    checkUserNumber.value = 0;
  }
  currentType.value = type;
  if (checkUserLst.value != undefined) {
    userList.value = originalUserList.value.filter(
      (itemA) => !checkUserLst.value.find((itemB) => itemA.id == itemB.id)
    );
  }
}
/**审批人类型change事件*/
function changeFlowType(values: any) {
  // currentType.value = values;
  flowType.value = values;
  if (current1.value != null) {
    checkUserLst.value = stampLst.value[current1.value].users;
    stampLst.value[current1.value].label = flowMenu.value[values - 1].label;
    stampLst.value[current1.value].user_type = values;
    checkUserNumber.value = checkUserLst.value.length;
  }
  if (values == 2) {
    flowOptionLst.value = positionLst.value;
    checkUserLst.value = [];
    checkUserNumber.value = 0;
  }
  if (current2.value != null) {
    promotionLst.value[current2.value].label = flowMenu.value[values - 1].label;
    promotionLst.value[current2.value].user_type = values;
    checkUserLst.value = promotionLst.value[current2.value].users;
    checkUserNumber.value = checkUserLst.value.length;
  }
  if (values == 3) {
    flowOptionLst.value = roleLst.value;
    checkUserLst.value = [];
    checkUserNumber.value = 0;
  }
  if (current3.value == true) {
    menuLabel.value = flowMenu.value[values - 1].label;
    ccPromotionLst.value.user_type = values;
    ccType.value = values;
    if (values == 1) {
      checkUserLst.value = ccPromotionLst.value.users;
      checkUserNumber.value = checkUserLst.value.length;
    }
  }
}
function changeUserType(values: any) {
  if (flowType.value == 2 || flowType.value == 3) {
    if (current1.value != null) {
      checkUserLst.value = [];
      checkUserNumber.value = 2;
      stampLst.value[current1.value].user_ids = values;
      console.log(stampLst.value[current1.value].user_ids, values);
    }
    if (current2.value != null) {
      checkUserLst.value = [];
      checkUserNumber.value = 2;
      promotionLst.value[current2.value].user_ids = values;
    }
    if (current3.value == true) {
      checkUserLst.value = [];
      checkUserNumber.value = 2;
      ccPromotionLst.value.user_ids = values;
    }
  }
}
watch(formData, (newVal) => {
  if (currentType.value == 1) {
    if (newVal.approval_type != undefined) {
      stampLst.value[current1.value].approval_type = newVal.approval_type;
    }
  }
});
/**点击审批人类型事件*/
function flowTab(item: any, index: number) {
  checkUserLst.value = [];
  if (item.type == 1) {
    if (index == current1.value) {
      current1.value = null;
      formData.type = flowType.value = undefined;
      formData.approval_type = undefined;
      currentType.value = 0;
    } else {
      current1.value = index;
      currentType.value = item.type;
    }
    current3.value = false;
    current2.value = null;
    if (current1.value != null) {
      if (stampLst.value[current1.value] != undefined) {
        checkUserLst.value = stampLst.value[current1.value].users;
        formData.type = flowType.value =
          stampLst.value[current1.value].user_type;
        formData.approval_type = stampLst.value[current1.value].approval_type;
        if (formData.type != 1) {
          checkUserIds.value = stampLst.value[current1.value].user_ids;
        }
      } else {
        formData.type = flowType.value = undefined;
        formData.approval_type = undefined;
      }
    } else {
      formData.type = flowType.value = undefined;
      formData.approval_type = undefined;
    }
  }
  if (item.type == 2) {
    if (index == current2.value) {
      current2.value = null;
      formData.type = flowType.value = undefined;
      formData.approval_type = undefined;
      currentType.value = 0;
    } else {
      current2.value = index;
      currentType.value = item.type;
    }
    current3.value = false;
    current1.value = null;
    if (current2.value != null) {
      checkUserLst.value = promotionLst.value[current2.value].users;
      formData.type = flowType.value =
        promotionLst.value[current2.value].user_type;
      formData.approval_type = promotionLst.value[current2.value].approval_type;
      if (formData.type != 1) {
        checkUserIds.value = promotionLst.value[current2.value].user_ids;
      }
    } else {
      formData.type = flowType.value = undefined;
      formData.approval_type = undefined;
    }
  }
  if (item.type == 3) {
    if (current3.value) {
      current3.value = false;
      formData.type = flowType.value = ccType.value = undefined;
      formData.approval_type = undefined;
      currentType.value = 0;
    } else {
      current3.value = true;
      currentType.value = 2;
    }
    current1.value = null;
    current2.value = null;
    formData.type = flowType.value = ccType.value;
    checkUserLst.value = ccPromotionLst.value.users;
    if (ccPromotionLst.value.user_type != undefined) {
      formData.type = flowType.value = ccPromotionLst.value.user_type;
      if (formData.type != 1) {
        checkUserIds.value = ccPromotionLst.value.user_ids;
      }
    } else {
      formData.type = flowType.value = undefined;
    }
    if (ccPromotionLst.value.approval_type != undefined) {
      formData.approval_type = ccPromotionLst.value.approval_type;
    } else {
      formData.approval_type = undefined;
    }
    ccPromotionLst.value.type = 2;
  }
  checkUserNumber.value = checkUserLst.value?.length;
  if (checkUserLst.value != undefined) {
    userList.value = originalUserList.value.filter(
      (itemA) => !checkUserLst.value.find((itemB) => itemA.id == itemB.id)
    );
  }
}

/** 组织架构树 */
function orgQuery() {
  orgTree()
    .then(({ data }) => {
      orgTreeData.value = data;
      const options: OptionType = orgTreeData.value[0];
      queryUserParams.id =
        typeof options.value === "string"
          ? parseInt(options.value)
          : options.value;
      getUserPage(queryUserParams)
        .then(({ data }) => {
          userList.value = originalUserList.value = data.items;
          totalUser.value = data.total;
        })
        .finally(() => {});
    })
    .finally(() => {});
}

function getPositionQuery() {
  getPositionAll()
    .then(({ data }) => {
      positionLst.value = data;
    })
    .finally(() => {});
}

function getRoleQuery() {
  getRoleOptions()
    .then(({ data }) => {
      roleLst.value = data;
    })
    .finally(() => {});
}

/**选择审批人员*/
function addUser(user?: UserPageVO, type?: string, isAll?: boolean) {
  if (user != undefined) {
    if (type === "add") {
      if (user.id != undefined) {
        if (currentType.value == 1) {
          stampLst.value[current1.value].user_ids.push(user.id);
          stampLst.value[current1.value].users.push(user);
          checkUserLst.value = stampLst.value[current1.value].users;
        } else {
          if (promotionLst.value.length > 0 && !current3.value) {
            promotionLst.value[current2.value].user_ids.push(user.id);
            promotionLst.value[current2.value].users.push(user);
            checkUserLst.value = promotionLst.value[current2.value].users;
          }
          if (current3.value) {
            ccPromotionLst.value.user_ids.push(user.id);
            ccPromotionLst.value.users.push(user);
            checkUserLst.value = ccPromotionLst.value.users;
          }
        }
      }
      if (userList.value != undefined) {
        userList.value = userList.value.filter((item) => {
          return item.id !== user.id;
        });
      }
    } else {
      if (isAll === true) {
        if (userList.value != undefined) {
          const mergedArray: UserPageVO[] = [
            ...userList.value,
            ...stampLst.value[current1.value].users,
            ...promotionLst.value[current2.value].users,
          ];
          userList.value = [
            ...new Map(mergedArray.map((item) => [item.id, item])).values(),
          ];
        }
        if (currentType.value == 1) {
          stampLst.value[current1.value].user_ids = [];
          stampLst.value[current1.value].users = [];
        } else {
          promotionLst.value[current2.value].user_ids = [];
          promotionLst.value[current2.value].users = [];
        }
        checkUserLst.value = [];
      } else {
        if (checkUserLst.value != undefined) {
          checkUserLst.value = checkUserLst.value.filter((item) => {
            return item.id !== user.id;
          });
        }
        if (currentType.value == 1) {
          stampLst.value[current1.value].user_ids = stampLst.value[
            current1.value
          ].user_ids.filter((item) => {
            return item !== user.id;
          });
          stampLst.value[current1.value].users = stampLst.value[
            current1.value
          ].users.filter((item) => {
            return item.id !== user.id;
          });
        } else {
          if (!current3.value) {
            promotionLst.value[current2.value].user_ids = promotionLst.value[
              current2.value
            ].user_ids.filter((item) => {
              return item !== user.id;
            });
            promotionLst.value[current2.value].users = promotionLst.value[
              current2.value
            ].users.filter((item) => {
              return item.id !== user.id;
            });
          } else {
            ccPromotionLst.value.user_ids =
              ccPromotionLst.value.user_ids.filter((item) => {
                return item !== user.id;
              });
            ccPromotionLst.value.users = ccPromotionLst.value.users.filter(
              (item) => {
                return item.id !== user.id;
              }
            );
          }
        }
        if (userList.value != undefined) {
          //先移除后添加
          userList.value = userList.value.filter((item) => {
            return item.id !== user.id;
          });
        }
        if (userList.value != undefined) {
          userList.value?.push(user);
        }
      }
    }
    checkUserNumber.value =
      checkUserLst.value != undefined ? checkUserLst.value.length : 0;
  }
}

/*** 确认选择*/
function confirmFlow() {
  const flowUserFormData: FlowUserForm = {
    flow_id: currentId.value,
    data: [],
  };
  stampLst.value.forEach((item, index) => {
    if (item.user_ids.length != 0) {
      flowUserFormData.data.push({
        type: item.type,
        user_ids: item.user_ids,
        user_type: item.user_type,
        approval_type: item.approval_type,
      });
    } else {
      ElMessage.error("请设置审批人");
      return;
    }
  });
  promotionLst.value.forEach((item, index) => {
    if (item.user_ids.length != 0) {
      flowUserFormData.data.push({
        type: item.type,
        user_ids: item.user_ids,
        user_type: item.user_type,
        approval_type: item.approval_type,
      });
    }
  });
  if (ccPromotionLst.value.user_ids.length > 0) {
    flowUserFormData.data.push({
      type: ccPromotionLst.value.type,
      user_ids: ccPromotionLst.value.user_ids,
      user_type: ccPromotionLst.value.user_type,
      approval_type: ccPromotionLst.value.approval_type,
    });
  } else {
    ElMessage.error("请设置抄送人");
    return;
  }
  const loadingFlow = ElLoading.service({
    lock: true,
    text: "提交中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  addFlowUser(flowUserFormData)
    .then(() => {
      viewDrawer.value = false;
      loadingFlow.close();
      ElMessage.success("设置成功");
      handleQuery();
    })
    .finally(() => loadingFlow.close());
}

/** 查询组织架构树下的用户*/
function handleOrg(tree: any) {
  queryUserParams.id = tree.id;
  getUserPage(queryUserParams)
    .then(({ data }) => {
      userList.value = data.items;
    })
    .finally(() => {});
}
function handleUserQuery() {
  getUserPage(queryUserParams)
    .then(({ data }) => {
      userList.value = data.items;
    })
    .finally(() => {});
}

function resetUserQuery() {
  queryUserFormRef.value.resetFields();
  queryUserParams.p = 1;
  handleUserQuery();
}

function openReviewDrawer(id: any) {
  viewDrawer.value = true;
  currentId.value = id;
  currentType.value = undefined;
  current1.value = undefined;
  current2.value = undefined;
  current3.value = undefined;
  menuLabel.value = "设置";
  currentType.value = 0;
  promotionLst.value = [];
  stampLst.value = [];
  ccPromotionLst.value.user_ids = [];
  ccPromotionLst.value.users = [];
  ccPromotionLst.value.user_type = undefined;
  ccPromotionLst.value.approval_type = undefined;
  checkUserLst.value = [];
  checkUserIds.value = [];
  formData.type = undefined;
  formData.approval_type = undefined;
  flowType.value = 0;
  getFlowUserForm(id)
    .then(({ data }) => {
      if (data.stampLst.length > 0) {
        stampLst.value = data.stampLst;
        current1.value = 0;
        currentType.value = 1;
        formData.type = data.stampLst[0].user_type;
        formData.approval_type = data.stampLst[0].approval_type;
        flowType.value = data.stampLst[0].user_type;
        checkUserLst.value = data.stampLst[0].users;
        checkUserNumber.value = data.stampLst[0].users.length;
        if (data.stampLst[0].user_type != 1) {
          checkUserIds.value = data.stampLst[0].user_ids;
        }
      } else {
        stampLst.value.push({
          type: 1,
          title: "审批人",
          label: "设置",
          user_ids: [],
          users: [],
          user_type: undefined,
          approval_type: undefined,
        });
      }
      if (data.promotionLst.length > 0) {
        if (data.promotionLst.length == 1) {
          menuLabel.value = data.promotionLst[0].label;
          ccPromotionLst.value = data.promotionLst[0];
          if (data.promotionLst[0].user_type != 1) {
            checkUserIds.value = data.promotionLst[0].user_ids;
          }
        } else {
          stampLst.value = data.promotionLst;
          if (data.promotionLst[0].user_type != 1) {
            checkUserIds.value = data.promotionLst.user_ids;
          }
        }
      }
      if (flowType.value == 2) {
        flowOptionLst.value = positionLst.value;
      }
      if (flowType.value == 3) {
        flowOptionLst.value = roleLst.value;
      }
    })
    .finally(() => {});
}

/** 查询 */
function handleQuery() {
  loading.value = true;
  getFlowPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

async function loadOptions() {
  getOptions().then((response) => {
    options.value = response.data;
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id
 */
async function openDialog(id?: any) {
  dialog.visible = true;
  await loadOptions();
  // 表单弹窗
  if (id) {
    dialog.title = "修改";
    getFlowForm(id).then(({ data }) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增";
  }
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.is_hid = 0;
  handleQuery();
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    loading.value = true;
    if (valid) {
      formData.approval_type = undefined;
      const ids = formData.id;
      if (ids) {
        updateFlow(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        addFlow(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleQuery();
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteFlow({ ids: ids }).then(() => {
      handleQuery();
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

function categoryType(value: any) {
  isShowForm.value = value == 2;
}

/** 排序 */
function handleSortChange(data: any) {
  const { prop, order } = data;
  if (prop === "id") {
    if (order === "ascending") {
      queryParams.sort = "+id";
    } else {
      queryParams.sort = "-id";
    }
    handleQuery();
  }
}

onMounted(() => {
  handleQuery();
  orgQuery();
  getPositionQuery();
  getRoleQuery();
});
</script>
<style lang="scss" scoped>
::v-deep(.el-tree-node__content) {
  height: 38px !important;
  line-height: 38px !important;
  border-radius: 8px !important;
}
.flow {
  width: 300px;
}
.flow-pr {
  position: relative;
  height: 158px;
}
.flow-container {
  padding: 13px 8%;
  border-radius: 4px;
  background: var(--el-fill-color-light);
}
.flow-container:hover {
  border: 1px solid #409eff;
  background-color: #ffffff;
}
.flow-container.active {
  background-color: #f5f7fa;
  border: 1px solid #409eff;
  color: #409eff;
}
.flow-line {
  width: 2px;
  top: 58px;
  bottom: 58px;
  left: 50%;
  position: absolute;
  border-color: inherit;
  height: 100px;
  background-color: var(--el-text-color-placeholder);
}
.stamp-close {
  position: absolute;
  top: -18px;
  right: -10px;
}
.flow-line-inner {
  transition-delay: -150ms;
  border-width: 0;
  height: 0;
}
.flow-add-button {
  position: absolute;
  top: 60%;
  left: 45%;
}
.flow-line-promotion {
  width: 2px;
  top: 58px;
  bottom: 58px;
  left: 50%;
  position: absolute;
  border-color: inherit;
  height: 50px;
  background-color: var(--el-text-color-placeholder);
}
.flow-add-button-promotion {
  position: absolute;
  bottom: 1px;
  left: 45%;
}
.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}
.message-avatar {
  display: inline-block;
  position: relative;
  margin: 10px 0;
}
.message-avatar .remove-user {
  position: absolute;
  right: 0;
  top: -10px;
  color: var(--el-color-danger);
  cursor: pointer;
}
.role-avatar {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
